package com.wuge.cart.controller;

import com.wuge.cart.interceptor.UserInterceptor;
import com.wuge.cart.service.CartService;
import com.wuge.cart.to.UserInfoTo;
import com.wuge.cart.vo.CartItemVo;
import com.wuge.cart.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    @RequestMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("num")Integer num){
        cartService.countItem(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @RequestMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @RequestMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("checked")Integer checked){
     cartService.changeCheck(skuId,checked);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @RequestMapping("/cart.html")
    public String cartList(Model model){
        CartVo cartVo = new CartVo();
        cartVo.setItems(cartService.list());
        model.addAttribute("cart",cartVo);
        return "cartList";
    }

    @RequestMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItemVo> currentUserCartItems(){
        List<CartItemVo>  cartItemVos=cartService.currentlist();
        return cartItemVos;
    }
    @RequestMapping("/addCartItem")
    public String addCartItem(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes){
//        防止重复添加,直接重定向
        CartItemVo cartItemVo=cartService.addSku(skuId,num);
        redirectAttributes.addAttribute("skuId",cartItemVo.getSkuId());
        return "redirect:http://cart.gulimall.com/add";
    }
    @RequestMapping("/add")
    public String add(@RequestParam("skuId") Long skuId, Model model){
       CartItemVo cartItemVo=cartService.getCartItem(skuId);
       model.addAttribute("cartItem",cartItemVo);
       return "success";
    }
}
